<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\ScoreRuleController;
use App\Models\Scenic;
use App\Models\ScenicType;
use App\Models\ScenicWorks;
use App\Models\UserInfo;
use App\Validate\ScenicWorksValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 景点打卡作品
 */
class ScenicWorksController extends CommonController
{
    protected $score_type = '6';

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ScenicWorks();
        $this->validate = new ScenicWorksValidate();
    }

    /**
     * 列表
     * @param scenic_id int 景点id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(作品名称，微信昵称)
     * @param status int 审核状态 作品状态 1.已通过   2.未通过   3.未审核(默认)   0全部
     * @param start_time 筛选开始时间 2020-10-10 23:59:59
     * @param end_time 筛选结束时间 2020-10-12 23:59:59
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $scenic_id = request()->scenic_id;
        $status = request()->status;
        $keywords = request()->keywords;
        $start_time = request()->start_time;
        $end_time = request()->end_time;


        $status = empty($status) ? [1, 2, 3] : [$status];
        $res = $this->model->lists($scenic_id, null, null, $keywords, $status, null, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据", "YES");
        }

        $ids = [];
        foreach ($res['data'] as $key => $val) {
            $ids[] = $val['id'];
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            //    $res['data'][$key]['type_name'] = ScenicType::where('id', $val['type_id'])->value('name');
            $user_info = UserInfo::getWechatField($val['user_id'], ['nickname', 'head_img']);
            $res['data'][$key]['head_img'] = $user_info['head_img'];
            $res['data'][$key]['nickname'] = $user_info['nickname'];
        }

        $this->model->where('scenic_id', $scenic_id)->whereIn('id', $ids)->update(['is_look' => 2]);

        $res = $this->disPageData($res);

        //获取总投票量
        $res['total_vote_num'] = $this->model->getTotalVoteNumber($scenic_id);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 作品id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //用于获取下一个作品
        $id = $this->request->id;

        $res = $this->model->detail($id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        // $res->is_look = 1;
        // $res->save(); //改为已查看

        $user_info = UserInfo::getWechatField($res['user_id'], ['head_img', 'nickname']);
        $res['nickname'] = $user_info['nickname'];
        $res['head_img'] = $user_info['head_img'];

        return $this->returnApi(200, "获取成功", true, $res->toArray());
    }

    /**
     * 审核作品
     * @param id int 作品id
     * @param status int 状态    1.通过   2.未通过
     * @param reason string 拒绝原因
     */
    public function worksCheck()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('works_check')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $id = $this->request->id;
        $status = $this->request->status;
        $reason = $this->request->reason ? $this->request->reason : null;

        if ($status == 2 && !$reason) {
            return $this->returnApi(202, '请填写拒绝原因');
        }

        $works = $this->model->find($id);
        $old_status = $works->status;
        if (!$works) {
            return $this->returnApi(202, '参数传递错误');
        }


        $works->status = $status;
        $works->reason = $reason;

        DB::beginTransaction();
        try {
            /*消息推送*/
            $check_msg = $works->status == 1 ? '审核通过' : '审核未通过';
            if ($works->status == 1) {
                $system_id = $this->systemAdd('景点打卡：您打卡的作品' . $check_msg, $works->user_id, $works->account_id, 58, intval($works->id), '作品：【' . $works->title . '】' . $check_msg);
            } else {
                $system_id = $this->systemAdd('景点打卡：您打卡的作品' . $check_msg, $works->user_id, $works->account_id, 58, intval($works->id), '作品：【' . $works->title . '】' . $check_msg . '，拒绝理由为：' . $reason);
            }

            /**执行积分规则 */
            //如果现在状态不是待审核，都不管积分
            // if (($old_status == 3 && $status == 2) && !empty($works->score)) {
            //     $scoreRuleObj = new ScoreRuleController();
            //     $score_msg = $scoreRuleObj->getScoreMsg($works->score);
            //     $scoreRuleObj->scoreReturn($this->score_type, $works->score, $works->user_id, $works->account_id, $check_msg . '，' . $score_msg . ' ' . abs($works->score) . ' 积分', $system_id);
            // }

            /**执行积分规则 */
            //如果现在状态不是待审核，都不管积分，积分统一采用审核时操作，
            if ($old_status == 3 && $status == 1) {
                $is_reader = Scenic::where('id', $works->scenic_id)->value('is_reader');
                if (config('other.is_need_score') === true  && $is_reader == 1) {
                    $scoreRuleObj = new ScoreRuleController();
                    $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $works->user_id, $works->account_id);
                    if ($score_status['code'] == 202 || $score_status['code'] == 203) throw new Exception($score_status['msg']);
                    if ($score_status['code'] == 200) {
                        $scoreRuleObj->scoreChange($score_status, $works->user_id, $works->account_id, $system_id); //添加积分消息
                    }
                }
            }


            $works->save();

            $check_msg = $works->status == 1 ? '已通过' : '已拒绝';

            DB::commit();
            return $this->returnApi(200, $check_msg, true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }


    /**
     * 违规 与 取消违规操作
     * @param id int 申请id
     * @param reason string 违规原因
     */
    public function violateAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('violate_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $res = $this->model->violateAndCancel($this->request->id, $this->request->reason);

            /*消息推送*/
            if ($res->is_violate == 2) {
                $system_id = $this->systemAdd('景点打卡已违规', $res->user_id, $res->account_id, 59, $res->id, '您发布的景点打卡：【' . $res->title . '】已违规，违规理由为：' . $this->request->reason);

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg($res->score);
                //     $score_rule->scoreReturn($this->score_type, $res->score,$res->user_id, $res->account_id, '景点打卡已违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id);
                // }
            } else {
                $system_id = $this->systemAdd('景点打卡已取消违规', $res->user_id, $res->account_id, 59, $res->id, '您发布的景点打卡：【' . $res->title . '】已取消违规');

                // if (!empty($res->score)) {
                //     $score_rule = new ScoreRuleController();
                //     $score_msg = $score_rule->getScoreMsg(-$res->score); //相反积分
                //     $score_rule->scoreReturn($this->score_type, $res->score,$res->user_id, $res->account_id, '景点打卡已违规，' . $score_msg . ' ' . abs($res->score) . ' 积分', $system_id);
                // }
            }

            // 提交事务
            DB::commit();
            return $this->returnApi(200, "操作成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
